<script setup lang="ts">
import { reactive, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { useAccountStore } from "@/stores/account";
import { handleToPage } from "@/utils";

/** 登陆成功跳转页面路径 */
let redirectPath = "/pages/index/index";

onLoad((options) => {
  if (options?.redirect) redirectPath = decodeURIComponent(options.redirect);
});

/** 表单数据 */
const formData = reactive({
  phone: "",
  password: "",
  code: ""
});

/** 校验规则 */
const formRules = {
  username: {
    rules: [
      {
        required: true,
        errorMessage: "请输入账户",
      },
      {
        minLength: 1,
        maxLength: 30,
        errorMessage: "账户长度在{minLength}到{maxLength}个字符",
      },
    ],
  },
  password: {
    rules: [
      {
        required: true,
        errorMessage: "请输入正确的密码",
      },
      {
        minLength: 6,
        errorMessage: "密码长度大于{minLength}个字符",
      },
    ],
  },
  phone: {
    rules: [
      {
        required: true,
        errorMessage: "请输入正确手机号码，未注册手机号将自动注册",
      },
      {
        minLength: 6,
        errorMessage: "手机号长度为{minLength}个数字",
      },
    ],
  },
  code: {
    rules: [
      {
        required: true,
        errorMessage: "请输入验证码",
      },
      {
        minLength: 6,
        errorMessage: "密码长度大于{minLength}个字符",
      },
    ],
  },
};

/** uni-forms 组件实例 */
const formRef = ref<InstanceType<UniHelper.UniForms> | null>(null);

const loading = ref(false);

const agreed = ref(false);

const accountStore = useAccountStore();

/** 登陆成功，重回来源页面 */
function loginSuccessAfter() {
  uni.redirectTo({
    url: redirectPath,
    fail: ({ errMsg }) => {
      if (/tab/.test(errMsg)) {
        // 来源为tabbar页
        uni.switchTab({ url: redirectPath });
      } else {
        console.error(errMsg);
      }
    },
  });
}

/** 提交表单 */
function submitForm() {
  // 根据loading防止重复提交
  if (loading.value) return;
  // 表单校验
  formRef.value?.validate &&
    formRef.value.validate(async (err: any) => {
      // 如果校验成功 ，err 返回 null
      if (err) return false;

      loading.value = true;
      // 调用登陆接口
      await accountStore.login(formData).finally(() => {
        loading.value = false;
      });

      loginSuccessAfter();
    });
}

/** 小程序登录 */
async function loginMP() {
  await accountStore.loginMP();
  loginSuccessAfter();
}
</script>

<template>
  <view class="relative overflow-hidden">
    <uv-navbar title="名律堂" placeholder autoBack></uv-navbar>
    <image class="block h-10 w-36 m-(x-auto t-17 b-3)" src="https://static.minglvtang.com/images/logo.png" />
    <view class="text-(lg center black/80) mb-10">欢迎使用名律堂</view>
    <view class="mx-6 grid gap-5">
      <!-- #ifdef H5 -->
      <uni-forms ref="formRef" label-width="0" :model="formData" :rules="formRules">
        <uni-forms-item name="phone">
          <view class="h-10 flex items-center border-b-(~ solid black/8)">
            <view class="px-2 flex items-center">+86 <view class="i-ri-arrow-down-s-fill"></view></view>
            <uni-easyinput :inputBorder="false" v-model="formData.phone" type="text" placeholder="请输入手机号码" />
          </view>
          <view class="mt-2 text-xs text-black/60">未注册手机号将自动注册</view>
        </uni-forms-item>
        <uni-forms-item name="code">
          <view class="h-10 flex items-center border-b-(~ solid black/8)">
            <uni-easyinput :inputBorder="false" v-model="formData.code" type="text" placeholder="请输入验证码" />
            <view class="p-2 text-#253851">获取验证码</view>
          </view>
          <view class="mt-2 text-xs text-#EA0000">验证码错误</view>
        </uni-forms-item>
      </uni-forms>

      <uv-button
        type="primary"
        shape="circle"
        size="large"
        text="登录"
        :custom-style="{
          fontSize: '18px',
          backgroundImage: 'linear-gradient(to right, #FF920D, #FFCF0D)',
          height: '48px',
          borderColor: 'transparent'
        }"
        :loading="loading"
        @click="submitForm"
      ></uv-button>
      <!-- #endif -->
      
      <!-- #ifdef MP-WEIXIN -->
      <uv-button
        type="primary"
        shape="circle"
        size="large"
        text="一键登录"
        :custom-style="{
          fontSize: '18px',
          backgroundImage: 'linear-gradient(to right, #FF920D, #FFCF0D)',
          height: '48px',
          borderColor: 'transparent'
        }"
        :disabled="!agreed"
        :loading="loading"
        @click="loginMP()"
      ></uv-button>
      <!-- #endif -->
    </view>

    <view class="flex items-center justify-center mt-4 mx-6">
      <view class="size-3.5 rounded-full border-(~ solid black/30)" v-show="!agreed" @click="agreed = !agreed"></view>
      <view class="size-3.5 rounded-full border-(~ solid #FBCD38) flex items-center justify-center" v-show="agreed" @click="agreed = !agreed">
        <view class="size-2 rounded-full bg-#FBCD38"></view>
      </view>
      <view class="text-(xs black/60) ml-2" @click="agreed = !agreed">已阅读并同意</view>
      <view class="text-(xs black/80)" @click="handleToPage(`/pages/account/agreement?type=user`)">《用户服务协议》</view>
      <view class="text-(xs black/60)">、</view>
      <view class="text-(xs black/80)" @click="handleToPage(`/pages/account/agreement?type=privacy`)">《隐私政策》</view>
    </view>
  </view>
</template>

<style>
page {
  background-color: #ffffff;
  background-image: none;
}
</style>
